#include "avatarselector.h"
#include "ui_avatarselector.h"

#include "Business/businessuser.h"
#include <AppConfig/appconfig.h>
#include "Business/inputhandler.h"

AvatarSelector::AvatarSelector(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::AvatarSelector)
{
    ui->setupUi(this);

    ui->labelAvatar->setFixedSize(QSize(128, 128));
    AppConfig& config = AppConfig::getInstance();
    // get avatar
    User& self = BusinessUser::getInstance().getTargetUser(config.runtimeValue("Account"));
    int avatar = self["Avatar"];

    QString path = getAvatarPath(avatar);
    qDebug() << path;
    QPixmap icon(path);
    ui->labelAvatar->setPixmap(icon);
    ui->labelAvatar->show();

    for (int i = 1; i <= 9 ; i ++) {
        QString avatarPath = getAvatarPath(i);
        QIcon avatar(avatarPath);
        ui->comboBoxAvatar->addItem(avatar, QString::number(i));
    }

    ui->labelPreview->setFixedSize(QSize(64, 64));

}

AvatarSelector::~AvatarSelector()
{
    delete ui;
}

QString AvatarSelector::getAvatarPath(int index)
{
    if (index < 1 || index > 9) {
        index = 1;
    }
    return ":/icon/avatar/" + QString::number(index) + ".svg";
}

void AvatarSelector::on_comboBoxAvatar_currentIndexChanged(int index)
{
    _avatar = index + 1;
    QString path = getAvatarPath(_avatar);
    QPixmap icon(path);
    ui->labelPreview->setPixmap(icon);
}


void AvatarSelector::on_btnAccept_clicked()
{
    QJsonObject in, out;
    in["Avatar"] = _avatar;
    InputHandler::getInstance()["AvatarSelector::on_btnAccept_clicked"](in, out);
    emit updateAvatar(_avatar);
    // update choosed avatar
    QString path = getAvatarPath(_avatar);
    QPixmap icon(path);
    ui->labelAvatar->setPixmap(icon);
}


void AvatarSelector::on_btnCancel_clicked()
{
    this->hide();
}

